<template>
  <div class="guide-tour-wrapper">
    <!-- 引导遮罩 -->
    <teleport to="body">
      <transition name="fade">
        <div v-if="isActive" class="guide-overlay" @click="skipTour">
          <!-- 高亮区域 -->
          <div class="guide-highlight" :style="highlightStyle"></div>
          
          <!-- 引导提示框 -->
          <transition name="slide-fade">
            <div v-if="currentStep" class="guide-tooltip" :style="tooltipStyle">
              <div class="tooltip-header">
                <span class="step-number">步骤 {{ stepIndex + 1 }}/{{ steps.length }}</span>
                <el-button text @click="skipTour" class="close-btn">
                  <el-icon><Close /></el-icon>
                </el-button>
              </div>
              
              <div class="tooltip-content">
                <h3>{{ currentStep.title }}</h3>
                <p>{{ currentStep.description }}</p>
                
                <!-- 特殊交互提示 -->
                <div v-if="currentStep.action" class="action-hint">
                  <el-icon><InfoFilled /></el-icon>
                  <span>{{ currentStep.action }}</span>
                </div>
              </div>
              
              <div class="tooltip-footer">
                <el-button v-if="stepIndex > 0" size="small" @click="prevStep">
                  <el-icon><ArrowLeft /></el-icon>
                  上一步
                </el-button>
                
                <div class="progress-dots">
                  <span
                    v-for="(step, idx) in steps"
                    :key="idx"
                    class="dot"
                    :class="{ active: idx === stepIndex, completed: idx < stepIndex }"
                    @click="goToStep(idx)"
                  ></span>
                </div>
                
                <el-button
                  v-if="stepIndex < steps.length - 1"
                  type="primary"
                  size="small"
                  @click="nextStep"
                >
                  下一步
                  <el-icon><ArrowRight /></el-icon>
                </el-button>
                <el-button
                  v-else
                  type="success"
                  size="small"
                  @click="completeTour"
                >
                  完成
                  <el-icon><CircleCheck /></el-icon>
                </el-button>
              </div>
            </div>
          </transition>
        </div>
      </transition>
    </teleport>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import {
  Close,
  InfoFilled,
  ArrowLeft,
  ArrowRight,
  CircleCheck
} from '@element-plus/icons-vue'

const props = defineProps({
  tourKey: {
    type: String,
    required: true
  },
  steps: {
    type: Array,
    required: true
  },
  autoStart: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['complete', 'skip'])

const isActive = ref(false)
const stepIndex = ref(0)
const highlightStyle = ref({})
const tooltipStyle = ref({})

const currentStep = computed(() => props.steps[stepIndex.value])

// 检查引导是否已完成
const checkTourCompleted = () => {
  const completed = localStorage.getItem(`tour_completed_${props.tourKey}`)
  return completed === 'true'
}

// 开始引导
const startTour = async () => {
  if (checkTourCompleted() && !props.autoStart) {
    return
  }
  
  isActive.value = true
  stepIndex.value = 0
  await nextTick()
  updateHighlight()
}

// 更新高亮区域和提示框位置
const updateHighlight = async () => {
  await nextTick()
  
  const step = currentStep.value
  if (!step || !step.element) return
  
  const element = document.querySelector(step.element)
  if (!element) {
    console.warn(`Element not found: ${step.element}`)
    return
  }
  
  const rect = element.getBoundingClientRect()
  const padding = 8
  
  // 设置高亮区域
  highlightStyle.value = {
    left: `${rect.left - padding}px`,
    top: `${rect.top - padding}px`,
    width: `${rect.width + padding * 2}px`,
    height: `${rect.height + padding * 2}px`,
    borderRadius: step.borderRadius || '8px'
  }
  
  // 计算提示框位置
  const tooltipPosition = calculateTooltipPosition(rect, step.placement || 'bottom')
  tooltipStyle.value = tooltipPosition
  
  // 滚动到元素
  element.scrollIntoView({ behavior: 'smooth', block: 'center' })
}

// 计算提示框位置
const calculateTooltipPosition = (rect, placement) => {
  const tooltipWidth = 360
  const tooltipHeight = 200
  const offset = 20
  
  let left, top
  
  switch (placement) {
    case 'top':
      left = rect.left + rect.width / 2 - tooltipWidth / 2
      top = rect.top - tooltipHeight - offset
      break
    case 'bottom':
      left = rect.left + rect.width / 2 - tooltipWidth / 2
      top = rect.bottom + offset
      break
    case 'left':
      left = rect.left - tooltipWidth - offset
      top = rect.top + rect.height / 2 - tooltipHeight / 2
      break
    case 'right':
      left = rect.right + offset
      top = rect.top + rect.height / 2 - tooltipHeight / 2
      break
    default:
      left = rect.left + rect.width / 2 - tooltipWidth / 2
      top = rect.bottom + offset
  }
  
  // 确保提示框在视窗内
  left = Math.max(20, Math.min(left, window.innerWidth - tooltipWidth - 20))
  top = Math.max(20, Math.min(top, window.innerHeight - tooltipHeight - 20))
  
  return {
    left: `${left}px`,
    top: `${top}px`,
    width: `${tooltipWidth}px`
  }
}

// 下一步
const nextStep = () => {
  if (stepIndex.value < props.steps.length - 1) {
    stepIndex.value++
    updateHighlight()
  }
}

// 上一步
const prevStep = () => {
  if (stepIndex.value > 0) {
    stepIndex.value--
    updateHighlight()
  }
}

// 跳转到指定步骤
const goToStep = (index) => {
  stepIndex.value = index
  updateHighlight()
}

// 完成引导
const completeTour = () => {
  localStorage.setItem(`tour_completed_${props.tourKey}`, 'true')
  isActive.value = false
  emit('complete')
}

// 跳过引导
const skipTour = () => {
  localStorage.setItem(`tour_completed_${props.tourKey}`, 'true')
  isActive.value = false
  emit('skip')
}

// 重置引导
const resetTour = () => {
  localStorage.removeItem(`tour_completed_${props.tourKey}`)
  startTour()
}

// 监听窗口大小变化
window.addEventListener('resize', () => {
  if (isActive.value) {
    updateHighlight()
  }
})

// 暴露方法
defineExpose({
  startTour,
  resetTour
})

onMounted(() => {
  if (props.autoStart) {
    setTimeout(startTour, 500)
  }
})
</script>

<style scoped>
.guide-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  z-index: 9999;
  transition: all 0.3s ease;
}

.guide-highlight {
  position: absolute;
  background: white;
  box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.6);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  pointer-events: auto;
  z-index: 10000;
}

.guide-tooltip {
  position: absolute;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  padding: 0;
  z-index: 10001;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.tooltip-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.step-number {
  font-size: 14px;
  color: #409eff;
  font-weight: 600;
}

.close-btn {
  padding: 4px;
}

.tooltip-content {
  padding: 20px;
}

.tooltip-content h3 {
  margin: 0 0 12px 0;
  font-size: 18px;
  color: #303133;
}

.tooltip-content p {
  margin: 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

.action-hint {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 16px;
  padding: 12px;
  background: #ecf5ff;
  border-radius: 6px;
  color: #409eff;
  font-size: 13px;
}

.tooltip-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;
}

.progress-dots {
  display: flex;
  gap: 8px;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #dcdfe6;
  cursor: pointer;
  transition: all 0.2s;
}

.dot.active {
  background: #409eff;
  transform: scale(1.2);
}

.dot.completed {
  background: #67c23a;
}

.dot:hover {
  transform: scale(1.1);
}

/* 动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.slide-fade-enter-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.slide-fade-leave-active {
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.slide-fade-enter-from {
  transform: translateY(-10px);
  opacity: 0;
}

.slide-fade-leave-to {
  transform: translateY(10px);
  opacity: 0;
}
</style>

